package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BusinessException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        if(StrUtil.isBlank(userLoginDTO.getCode())){
            throw new BusinessException(500,"登录异常");
        }
        //1. 发请求访问微信登录凭证校验接口
        HashMap<String, String> paraMap = new HashMap<>();
        paraMap.put("appid",weChatProperties.getAppid());
        paraMap.put("secret",weChatProperties.getSecret());
        paraMap.put("js_code",userLoginDTO.getCode());
        paraMap.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, paraMap);
        //解析响应的结果
        //2. 获取openid
        String openid = (String) JSON.parseObject(json).get("openid");
        if(StrUtil.isBlank(openid)){
            throw new BusinessException(500,"登录异常");
        }
        //3. 根据openid查询user表
        User user = userMapper.getByOpenId(openid);
        //4. 有：直接返回
        if(user != null){
            return user;
        }
        //5. 自动创建一个账号，返回
        user = new User();
        user.setOpenid(openid);
        userMapper.insert(user);
        return user;
    }
    }

